package com.yntx.usercenter.common.config;

import com.yntx.usercenter.authentication.util.HttpRequestUtil;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: WebMvc 拦截器
 *
 * @author Liziba
 * @version 1.0
 * @date 2022/12/20 2:57 PM
 * @since JDK 1.8
 */

public class WebMvcInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TenantUserContextHolder context = HttpRequestUtil.getTenantUserContextHolder(request);
        TenantUserContextHolder.set(context);
        // 分库键
        HintManager.clear();
        HintManager instance = HintManager.getInstance();
        instance.setDatabaseShardingValue(context.getTenantId());
        instance.setDataSourceName(context.getTenantId());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空
        TenantUserContextHolder.set(null);
        // 分库键
        HintManager.clear();
    }
}
